package com.lab.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lab.pojo.Operator;
import com.lab.service.OperatorService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/operator")
public class OperatorController {
    @Resource
    OperatorService operatorService;
    private Map<String,Object> result=new HashMap<String, Object>();
    /**
     * 查询所有学生信息
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping(value = "/listByPage")
    public Map<String,Object> listByPage(Integer page, Integer rows){
        //设置分页参数
        page=(page-1)*rows;
        PageHelper.offsetPage(page, rows);
        //查询所有数据
        List<Operator> list= operatorService.allOperators();

        //使用PageInfo封装查询结果
        PageInfo<Operator> pageInfo=new PageInfo<Operator>(list);
        for(Operator operator:list){
            if(operator.getState().equals("1")){
                operator.setState("正常");
            }else{
                operator.setState("停用");
            }
        }
        //从PageInfo对象取出查询结果
        //总记录数
        long total=pageInfo.getTotal();
        //当前页数据列表
        List<Operator> operatorList=pageInfo.getList();
        result.put("total", total);
        result.put("rows", operatorList);
        return result;
    }

    /**
     * 添加和修改
     * @param operator
     * @return
     */
    @RequestMapping(value="/saveOperator",method = RequestMethod.POST)
    public Map<String,Object> saveOperator(Operator operator){
        try {
            operatorService.saveOperator(operator);
            result.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return result;
    }

    /**
     * 数据回显
     * @param mid
     * @return
     */
    @RequestMapping(value="/findOperatorById",method = RequestMethod.GET)
    public Operator findOperatorById(Integer mid) {
        Operator operator= operatorService.findOperatorById(mid);
        return operator;
    }

    /**
     *删除数据
     * @param mid
     * @return
     */
    @RequestMapping(value="/deleteOperator",method = RequestMethod.DELETE)
    @ResponseBody
    public Map<String,Object> deleteOperator(Integer[] mid){
        try {
            operatorService.deleteOperator(mid);
            result.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return result;
    }
}
